package com.mf.ergate.web.security.provider;

import com.mf.ergate.web.security.MfUserDetails;
import org.apache.commons.codec.digest.Md5Crypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 用户名与密码认证
 * User: zhaoming
 * DateTime: 2018-05-27
 * To change this template use File | Settings | File Templates.
 **/
@Component
public class DbAuthenticationProvider implements AuthenticationProvider {

    public Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${salt}")
    private String salt;
    @Autowired
    private DbUserDetailsService dbUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        UserDetails userDetails = dbUserDetailsService.loadUserByUsername(username);
        if (userDetails == null) {
            throw new UsernameNotFoundException("用户不存在，禁止访问");
        } else if (((MfUserDetails) userDetails).isLocked()) {
            throw new LockedException("用户已锁定，禁止访问");
        }else if (!((MfUserDetails) userDetails).isEnable()) {
            throw new DisabledException("用户已停用，禁止访问");
        } else if (!Objects.equals(Md5Crypt.md5Crypt(password.getBytes(), salt), userDetails.getPassword())) {
            throw new BadCredentialsException("用户名与密码不匹配，禁止访问");
        }
        return new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
